package service

import (
	"choujiang/common/models"
	"choujiang/common/db"
	"fmt"
	"encoding/json"
	"time"
	"choujiang/common/utils"
)

const CATE_GAMES_CASH = "BoxKey::categamescash_"

type ResCateGames struct {
	Name  string       `json:"name"`
	Icon  string       `json:"icon"`
	Games []model.Game `json:"games"`
}

func GetCateGames(gameId string) []ResCateGames {
	res := make([]ResCateGames, 0)
	key := CATE_GAMES_CASH + gameId
	v := db.MainRedisClient.Exists(key)
	if v.Val() == 1 {
		s := db.MainRedisClient.Get(key)
		err := json.Unmarshal([]byte(s.Val()), &res)
		if err == nil {
			return res
		}
	}
	box := new(model.Box)
	_, err := db.MysqlEngine.Where("name = ?", gameId).Get(box)
	if err != nil || box == nil {
		fmt.Printf("Get box err ---------%v", err)
	}
	ids := []int64{}
	gameBox := make([]model.GameBox, 0)
	err = db.MysqlEngine.Where("box_id=?", box.Id).Find(&gameBox)
	if err != nil || len(gameBox) < 1 {
		fmt.Printf("Get gamebox err ---------%v", err)
	} else {
		for i := 0; i < len(gameBox); i++ {
			ids = append(ids, gameBox[i].GameId)
		}
	}
	categorys := make([]model.Categorys, 0)
	err = db.MysqlEngine.Where("status=?", 1).Find(&categorys)
	if err != nil {
		fmt.Printf("Get categorys err %s", err)
	}
	for i := 0; i < len(categorys); i++ {
		cateGames := make([]model.Game, 0)
		err = db.MysqlEngine.Join("INNER", "game_categorys", "game.id = game_categorys.gid").Where("game_categorys.cid=? and game.status=?", categorys[i].Id, 1).In("game.id", ids).Find(&cateGames)
		if err == nil {
			for i := 0; i < len(cateGames); i++ {
				cateGames[i].CateName = GetGameCategory(cateGames[i])
				cateGames[i].TagName = GetGameTag(cateGames[i])
				cateGames[i].Icon = utils.AddPrefix(cateGames[i].Icon)
				cateGames[i].QrCode = utils.AddPrefix(cateGames[i].QrCode)
			}
			icon := utils.AddPrefix(categorys[i].Icon)
			resCate := &ResCateGames{
				Name:  categorys[i].Name,
				Games: cateGames,
				Icon:  icon,
			}
			res = append(res, *resCate)
		}
	}
	if len(res) > 0 {
		jsonRes, err := json.Marshal(res)
		if err == nil {
			db.MainRedisClient.Set(key, jsonRes, time.Minute*10)
		}
	}
	return res
}
